package com.dotmedia.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dotmedia.dboperations.AdTemplateDatabaseOperations;
import com.dotmedia.entities.AdTemplate;

/**
 * This servlet returns the code of the template id which is passed to this servelt
 */
public class TemplateCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger("dotmedia.servlets");

	public TemplateCodeServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doMethod(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doMethod(request, response);
	}

	private void doMethod(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("IN method doMethod() of TemplateCodeServlet");
		response.setContentType("text/html");
		String adTemplateIdString = request.getParameter("adTemplateId");
		int adTemplateId = 0;
		logger.info("AdTemplateId received by the servlet: " + adTemplateIdString);
		try {
			adTemplateId = Integer.parseInt(adTemplateIdString);
			List<AdTemplate> adTemplateObjects = new AdTemplateDatabaseOperations().getAdTemplateEntitiesByAdTemplateId(adTemplateId);
			// now read the code of the first object and write it back to response
			for (int index = 0; index < adTemplateObjects.size(); index++) {
				AdTemplate currentAdTemplateObject = adTemplateObjects.get(index);
				response.getOutputStream().println(currentAdTemplateObject.getCode());
				logger.info("Wrote the code of the ad template object back to the response");
				break;
			}
		} catch (NumberFormatException e) {
			logger.error("NumberFormatException while converting ad template id passed to string. Message: " + e.getMessage());
		}
		logger.info("OUT method doMethod() of TemplateCodeServlet");
	}

}
